from django.db.models import fields
from django.template.defaultfilters import slugify


class AutoUniqueSlugField(fields.SlugField):
    def __init__(self, prepopulate_from, *args, **kwargs):
        self.prepopulate_from = prepopulate_from
        self.unique_together = kwargs.get("unique_together", "")
        if self.unique_together:
            del kwargs["unique_together"]
        super(AutoUniqueSlugField, self).__init__(*args, **kwargs)
    
    def pre_save(self, model_instance, add):
        if not add:
            return getattr(model_instance, self.attname)
            
        model, slug_field = model_instance.__class__, self.name
        slug_value = getattr(model_instance, self.prepopulate_from)
        
        orig_slug = slug = slugify(slug_value)
        
        query_args = {slug_field:slug}
        if self.unique_together:
            extra_arg = getattr(model_instance, self.unique_together)
            query_args[self.unique_together] = extra_arg
    
        index = 0
    
        while model.objects.filter(**query_args).exclude(id=model_instance.id).count():
            index += 1
            query_args[slug_field] = orig_slug + '-' + str(index)
        setattr(model_instance, self.attname, query_args[slug_field])
        return query_args[slug_field]